using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace PowerManager
{
	internal class WinApiWrapping
	{
		[DllImport("Kernel32.dll", SetLastError = true)]
		internal static extern bool CloseHandle(IntPtr hObject);

		[DllImport("advapi32.dll", SetLastError = true)]
		internal static extern bool InitiateSystemShutdown(string machineName, string message, int timeout, bool forceAppClosed, bool rebootAfterShutdown);

		[DllImport("user32.dll", SetLastError = true)]
		internal static extern bool ExitWindowsEx(ExitWindowsExFlags uFlags, ExitWindowsExReason dwReason);
		
		[DllImport("advapi32.dll", SetLastError = true)]
		internal static extern bool OpenProcessToken(IntPtr ProcessHandle, TokenAccess DesiredAccess, out IntPtr TokenHandle);

		[DllImport("advapi32.dll", SetLastError = true)]
		internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID pluid);

		[DllImport("advapi32.dll", SetLastError = true)]
		internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, out TOKEN_PRIVILEGES PreviousState, out int ReturnLength);

		[StructLayout(LayoutKind.Sequential)]
		internal struct LUID
		{
			public int LowPart;
			public int HighPart;
		}

		[StructLayout(LayoutKind.Sequential)]
		internal struct LUID_AND_ATTRIBUTES
		{
			public LUID Luid;
			public Privilege Attributes;
		}

		[StructLayout(LayoutKind.Sequential)]
		internal struct TOKEN_PRIVILEGES
		{
			public int PrivilegeCount;
			public LUID_AND_ATTRIBUTES Privileges;
		}

		internal enum Privilege : uint
		{
			SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001,
			SE_PRIVILEGE_ENABLED = 0x00000002,
			SE_PRIVILEGE_REMOVED = 0X00000004,
			SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
		}

		[Flags]
		internal enum TokenAccess
		{
			TOKEN_ASSIGN_PRIMARY = 0x0001,
			TOKEN_DUPLICATE = 0x0002,
			TOKEN_IMPERSONATE = 0x0004,
			TOKEN_QUERY = 0x0008,
			TOKEN_QUERY_SOURCE = 0x0010,
			TOKEN_ADJUST_PRIVILEGES = 0x0020,
			TOKEN_ADJUST_GROUPS = 0x0040,
			TOKEN_ADJUST_DEFAULT = 0x0080,
			TOKEN_ADJUST_SESSIONID = 0x0100
		}

		[Flags]
		internal enum ExitWindowsExFlags
		{
			EWX_LOGOFF = 0,
			EWX_SHUTDOWN = 0x00000001,
			EWX_REBOOT = 0x00000002,
			EWX_FORCE = 0x00000004,
			EWX_POWEROFF = 0x00000008,
			EWX_FORCEIFHUNG = 0x00000010
		}

		[Flags]
		internal enum ExitWindowsExReason
		{
			SHTDN_REASON_MAJOR_APPLICATION = 0x00040000,
			SHTDN_REASON_MAJOR_HARDWARE = 0x00010000,
			SHTDN_REASON_MAJOR_LEGACY_API = 0x00070000,
			SHTDN_REASON_MAJOR_OPERATINGSYSTEM = 0x00020000,
			SHTDN_REASON_MAJOR_OTHER = 0x00000000,
			SHTDN_REASON_MAJOR_POWER = 0x00060000,
			SHTDN_REASON_MAJOR_SOFTWARE = 0x00030000,
			SHTDN_REASON_MAJOR_SYSTEM = 0x00050000
		}
	}
}
